import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 300000 // 请求超时时间
})

const userProfileRequest = axios.create({
  baseURL: '/userprofileservice',
  timeout: 300000
})

// 异常拦截处理器
const errorHandler = (error) => {
  console.log(error);
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.data.code === 403) {
      notification.error({
        message: '禁止',
        description: data.msg
      })
    }
    if (error.response.data.code === 401) {
      notification.error({
        message: '登陆失效',
        description: error.response.data.msg
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

function addCommonParams(config){
  const token = storage.get(ACCESS_TOKEN)
  config.headers["Accept"] = "application/json"
  if (config.method !== 'get' && config.method !== 'delete') {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  }
  if (token) {
    config.headers['Authorization'] = 'bearer ' + token
  } else {
    config.headers['Authorization'] = ''
  }
  const org = store.getters.selectedOrg
  if (org && typeof org.id != null){
    if (typeof config.params === 'object'){
      config.params.orgId = org.id
    }else {
      config.params = {orgId:org.id}
    }
  }
  return config
}


// request interceptor
request.interceptors.request.use(config => {
  return addCommonParams(config)
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

// request interceptor
userProfileRequest.interceptors.request.use(config => {
  return addCommonParams(config)
}, errorHandler)

// response interceptor
userProfileRequest.interceptors.response.use((response) => {
  return response.data
}, errorHandler)


const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request, userProfileRequest)
  }
}




export default request

export {
  installer as VueAxios,
  request as axios,
  userProfileRequest as userProfileRequest
}
